package com.jt.www.common.service.impl;

import com.jt.www.common.service.RiskStartTimeService;
import com.jt.www.dao.mapper.policyattribute.RiskStartTimeConfigMapper;
import com.jt.www.model.policyattribute.RiskStartTimeConfig;
import com.jt.www.model.policyattribute.vo.RiskStartTimeVo;
import com.jt.www.util.DateUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import tk.mybatis.mapper.weekend.Weekend;
import tk.mybatis.mapper.weekend.WeekendCriteria;

import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
 * Created by shaoyn on 2020/02/28.
 */
@Service
public class RiskStartTimeServiceImpl implements RiskStartTimeService {

    @Autowired
    private RiskStartTimeConfigMapper riskStartTimeConfigMapper;

    @Override
    public RiskStartTimeVo getRiskStartTime(String productCode) {
        Date nowDate = new Date();

        Weekend<RiskStartTimeConfig> weekend = Weekend.of(RiskStartTimeConfig.class);
        WeekendCriteria<RiskStartTimeConfig, Object> criteria = weekend.weekendCriteria();
        criteria.andEqualTo(RiskStartTimeConfig::getProductCode, productCode);
        criteria.andEqualTo(RiskStartTimeConfig::getIsDeleted, "0");
        criteria.andLessThanOrEqualTo(RiskStartTimeConfig::getEffectStartDate, nowDate);
        criteria.andGreaterThanOrEqualTo(RiskStartTimeConfig::getEffectEndDate, nowDate);

        List<RiskStartTimeConfig> riskStartTimeConfigs = riskStartTimeConfigMapper.selectByExample(weekend);
        if (CollectionUtils.isEmpty(riskStartTimeConfigs)) {
            return null;
        }
        //取结果集中第一条记录
        RiskStartTimeConfig riskStartTimeConfig = riskStartTimeConfigs.get(0);

        return getRiskStartTime(riskStartTimeConfig, nowDate);
    }


    /**
     * 为参数日期 计算得到起期时间范围
     *
     * @param riskStartTimeConfig
     * @param date                日期
     * @return
     */
    private RiskStartTimeVo getRiskStartTime(RiskStartTimeConfig riskStartTimeConfig, Date date) {
        RiskStartTimeVo riskStartTimeVo = new RiskStartTimeVo();
        //最大倒签天数
        riskStartTimeVo.setMaxBackNum(riskStartTimeConfig.getMaxBackNum());
        //配置的 最早开始日期
        String earliestStartDate = conversion(riskStartTimeConfig.getEarliestStartDate(), date);
        //最大倒签天数 为空时做处理
        Integer maxBackNum = null == riskStartTimeConfig.getMaxBackNum() ? 365 : riskStartTimeConfig.getMaxBackNum();
        //倒签最多的天数后的日期
        Date backDate = DateUtils.add(
                date,
                Calendar.DATE, 0 - maxBackNum);

        //最早开始时间取其中最大的值
        if (StringUtils.isBlank(earliestStartDate)) {
            riskStartTimeVo.setEarliestStartDate(null);
        } else if (DateUtils.str2Date(earliestStartDate, DateUtils.DATE_FORMAT_YYYY_MM_DD).getTime() < backDate.getTime()) {
            riskStartTimeVo.setEarliestStartDate(DateUtils.converDate(backDate));
        } else {
            riskStartTimeVo.setEarliestStartDate(earliestStartDate);
        }

        //配置的 最晚开始日期
        String latestStartDate = conversion(riskStartTimeConfig.getLatestStartDate(), date);

        riskStartTimeVo.setLatestStartDate(latestStartDate);

        //配置的 默认开始日期
        String defaultStartDate = conversion(riskStartTimeConfig.getDefaultStartDate(), date);
        //如果最小开始日期和默认开始日期 其中1项为空
        if (StringUtils.isBlank(earliestStartDate) || StringUtils.isBlank(defaultStartDate)
                //或者如果默认开始日期大于最小开始日期
                || DateUtils.str2Date(earliestStartDate, DateUtils.DATE_FORMAT_YYYY_MM_DD).getTime() <
                DateUtils.str2Date(defaultStartDate, DateUtils.DATE_FORMAT_YYYY_MM_DD).getTime()) {
            //返回 默认开始日期
            riskStartTimeVo.setDefaultStartDate(defaultStartDate);
        } else {
            //如果最小开始日期大于 计算返回的默认开始日期  返回最小开始日期
            riskStartTimeVo.setDefaultStartDate(earliestStartDate);
        }

        //最小投保天数
        riskStartTimeVo.setInsuredMinNum(riskStartTimeConfig.getInsuredMinNum());
        //最大投保天数
        riskStartTimeVo.setInsuredMaxNum(riskStartTimeConfig.getInsuredMaxNum());


        return riskStartTimeVo;
    }


    /**
     * 将日期做转换
     *
     * @param dateStr
     * @param date
     * @return
     */
    private String conversion(String dateStr, Date date) {
        //如果没有配置 返回null
        if (StringUtils.isBlank(dateStr)) {
            return null;
        }
        //如果是T 返回传过来的日期
        if ("T".equals(dateStr)) {
            return DateUtils.converDate(date);
        } else if (dateStr.startsWith("T+")) {
            try {
                String[] dateArray = dateStr.replaceAll("\\s*", "").split("\\+");
                if (dateArray.length == 2) {
                    date = DateUtils.add(date, Calendar.DATE, Integer.parseInt(dateArray[1]));
                }
            } catch (Exception e) {
                //处理异常 直接反回当前 传过来的日期
            }
            return DateUtils.converDate(date);
        } else if (dateStr.startsWith("T-")) {
            try {
                String[] dateArray = dateStr.replaceAll("\\s*", "").split("-");
                if (dateArray.length == 2) {
                    date = DateUtils.add(date, Calendar.DATE, 0 - Integer.parseInt(dateArray[1]));
                }
            } catch (Exception e) {
                //处理异常 直接反回当前 传过来的日期
            }
            return DateUtils.converDate(date);
        }
        //返回配置的日期
        return dateStr;
    }


}
